package com.etone.smartAudit.service;

import com.alibaba.excel.EasyExcel;
import com.etone.smartAudit.domain.work.WorkOrder;
import com.etone.smartAudit.domain.work.WorkRectify;
import com.etone.smartAudit.domain.work.WorkRectifyTemplate;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.WorkRectifyMapper;
import com.etone.smartAudit.onlyoffice.util.WorkRectifyListener;
import com.etone.smartAudit.utils.Excel.MyEasyExcelUtils;
import com.etone.smartAudit.vo.workOrder.WorkRectifyTemplateVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 张任豪
 */
@AllArgsConstructor
@Service
@Slf4j
public class WorkRectifyTemplateService {

    private WorkOrderService workOrderService;

    private WorkRectifyMapper workRectifyMapper;

    private WorkOrderRectifyService workOrderRectifyService;

    public WorkRectifyTemplateVO batchRefusalTemplate(MultipartFile file) {
        try {
            WorkRectifyTemplateVO vo = new WorkRectifyTemplateVO();
            List<WorkRectifyTemplate> list = EasyExcel.read(file.getInputStream(), WorkRectifyTemplate.class,
                    new WorkRectifyListener(workOrderService)).sheet().doReadSync();
            Integer fail = Math.toIntExact(list.stream().filter(WorkRectifyTemplate::getIsError).count());
            Integer success = list.size() - fail;
            vo.setWorkRectifyTemplateList(list);
            vo.setFail(fail);
            vo.setSuccess(success);
            vo.setFileName(file.getOriginalFilename());
            vo.setFileSize(file.getSize());
            return vo;
        } catch (Exception e) {
            log.info("批量反馈导入失败{}", e.getMessage());
            throw new CustomParameterizedException("批量反馈信息失败,请检查格式是否有误");
        }
    }


    /**
     * 批量反馈导入模板
     *
     * @param ids
     * @param response
     */
    public void feedBackTemplate(List<Integer> ids, HttpServletResponse response) {
        if (ids.size() == 0) {
            throw new CustomParameterizedException("请选择工单");
        }
        List<WorkOrder> orders = workOrderService.listByIds(ids);
        List<WorkRectifyTemplate> list = new ArrayList<>();
        for (WorkOrder order : orders) {
            list.add(WorkRectifyTemplate.builder()
                    .rectifyCode(order.getRectifyCode())
                    .year(order.getYear())
                    .itemName(order.getItemName())
                    .itemTypeName(order.getItemTypeName())
                    .problemSummary(order.getProblemSummary())
                    .problemInfo(order.getProblemInfo())
                    .rectifyTips(order.getRectifyTips()).build());
        }
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("批量填写反馈模板" + ".xlsx", "UTF-8"));
            EasyExcel.write(response.getOutputStream(), WorkRectifyTemplate.class).registerWriteHandler(MyEasyExcelUtils.setHorizontalCellStyleStrategy()).sheet("填写反馈模板").doWrite(list);
        } catch (Exception e) {
            log.info("下载模板失败 :{}", e.getMessage());
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void saveAll(List<WorkRectifyTemplate> templates) {
        if (!templates.isEmpty()) {
            for (WorkRectifyTemplate template : templates) {
                if (!template.getIsError()) {
                    WorkRectify workRectify = workOrderRectifyService.getByWorkId(template.getWorkId());
                    BeanUtils.copyProperties(template, workRectify);
                    workRectifyMapper.updateById(workRectify);
                }
            }
        }
    }
}
